package com.sion.servicekeep;

import android.Manifest;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.util.Log;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    public static String selectedPackageName; // 全局变量
    private static final String TAG = "MainActivity";
    private Switch switchAutoStart;
    private Switch switchDaemonStart;
    private SharedPreferences sharedPreferences;
    private static final String PREF_NAME = "AppSettings";
    private static final String KEY_AUTO_START = "auto_start_enabled";
    private static final String KEY_DAEMON_START = "daemon_start_enabled";
    private static final String KEY_STARTUP_DELAY = "startup_delay"; // 新增键名
    private static final int REQUEST_NOTIFICATION_PERMISSION = 1001;
    private static final int REQUEST_BATTERY_OPTIMIZATION = 1002;
    private static final int REQUEST_USAGE_STATS_PERMISSION = 1003;
    private static final int REQUEST_OVERLAY_PERMISSION = 1004;
    private Button btnSelectApp;
    private TextView tvSelectedApp;
    private CheckBox cbShowSystemApps;
    private EditText etCheckInterval;
    private EditText etStartupDelay; // 新增变量
    public AppLauncher appLauncher;
    private Switch switchShowFloatingWindow;
    private EditText etFloatingWindowText;
    public boolean isDaemonCleared = false; // 新增标志位

    private static final String ACTION_CLEAR_PACKAGE_NAME = "com.sion.servicekeep.ACTION_CLEAR_PACKAGE_NAME";
    private static final String ACTION_CLOSE_TARGET_APP = "com.sion.servicekeep.ACTION_CLOSE_TARGET_APP";

    private BroadcastReceiver clearPackageNameReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_CLEAR_PACKAGE_NAME.equals(intent.getAction())) {
                clearSelectedPackageName();
            }
        }
    };
    private BroadcastReceiver closeTargetAppReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (ACTION_CLOSE_TARGET_APP.equals(intent.getAction())) {
                closeTargetApp();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.Selfstarting), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 初始化SharedPreferences
        sharedPreferences = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);

        // 检查是否由AutoStartReceiver启动
        String startedBy = getIntent().getStringExtra("startedBy");
        if ("AutoStartReceiver".equals(startedBy)) {
            Log.d(TAG, "Activity started by AutoStartReceiver");
        }

        // 请求必要权限
        requestNecessaryPermissions();

        // 初始化开关
        initAutoStartSwitch();
        initDaemonStartSwitch();

        // 检查当前AutoStartReceiver状态
        checkAutoStartReceiverStatus();

        // 初始化选择应用按钮和文本框
        btnSelectApp = findViewById(R.id.btnSelectApp);
        tvSelectedApp = findViewById(R.id.tvSelectedApp);
        cbShowSystemApps = findViewById(R.id.cbShowSystemApps);
        etCheckInterval = findViewById(R.id.etCheckInterval);
        etStartupDelay = findViewById(R.id.etStartupDelay); // 初始化



        // 设置默认目标程序
        if(!isDaemonCleared){
            // 设置默认间隔时间为5
            etCheckInterval.setText("5");
            selectedPackageName = "com.richard.yzdigithuman2d";

        }
//        selectedPackageName = "com.richard.yzdigithuman2d";
        tvSelectedApp.setText("小智同学 (" + selectedPackageName + ")");
        startAppMonitoringIfPossible();

        btnSelectApp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showAppListDialog();
            }
        });

        etCheckInterval.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    startAppMonitoringIfPossible();
                }
            }
        });

        // 初始化悬浮窗开关和输入框
        switchShowFloatingWindow = findViewById(R.id.switchShowFloatingWindow);
        etFloatingWindowText = findViewById(R.id.etFloatingWindowText);

        // 默认开启悬浮窗
        switchShowFloatingWindow.setChecked(true);
        requestOverlayPermission();

        switchShowFloatingWindow.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                requestOverlayPermission();
            } else {
                stopFloatingWindowService();
            }
        });

        // 注册广播接收器
        IntentFilter filter = new IntentFilter(ACTION_CLEAR_PACKAGE_NAME);
        // 直接使用 RECEIVER_NOT_EXPORTED，因为这是应用内部广播
        registerReceiver(clearPackageNameReceiver, filter, Context.RECEIVER_EXPORTED);

        // 注册广播接收器
        IntentFilter filter1 = new IntentFilter(ACTION_CLOSE_TARGET_APP);
        registerReceiver(closeTargetAppReceiver, filter1,Context.RECEIVER_EXPORTED);

        // 监听开机延迟启动时间输入框
        etStartupDelay.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    saveStartupDelay();
                }
            }
        });
    }

    private void saveStartupDelay() {
        String delayStr = etStartupDelay.getText().toString();
        int delay = 3; // 默认值
        try {
            delay = Integer.parseInt(delayStr);
        } catch (NumberFormatException e) {
            Log.e(TAG, "Invalid startup delay value: " + delayStr);
        }
        sharedPreferences.edit().putInt(KEY_STARTUP_DELAY, delay).apply();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        unregisterReceiver(clearPackageNameReceiver);
        unregisterReceiver(closeTargetAppReceiver);
    }

    private void startFloatingWindowService() {
        String floatingWindowText = etFloatingWindowText.getText().toString();
        Intent serviceIntent = new Intent(this, FloatingWindowService.class);
        serviceIntent.putExtra("floatingWindowText", floatingWindowText);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startForegroundService(serviceIntent);
        } else {
            startService(serviceIntent);
        }
    }

    private void stopFloatingWindowService() {
        Intent serviceIntent = new Intent(this, FloatingWindowService.class);
        stopService(serviceIntent);
    }

    private void showAppListDialog() {
        PackageManager packageManager = getPackageManager();
        List<PackageInfo> packageInfoList;

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            // Android 13 及以上版本
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            List<ResolveInfo> resolveInfoList = packageManager.queryIntentActivities(intent, PackageManager.MATCH_ALL);
            packageInfoList = new ArrayList<>();
            for (ResolveInfo resolveInfo : resolveInfoList) {
                try {
                    PackageInfo packageInfo = packageManager.getPackageInfo(resolveInfo.activityInfo.packageName, 0);
                    packageInfoList.add(packageInfo);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        } else {
            // Android 13 以下版本
            packageInfoList = packageManager.getInstalledPackages(0);
        }

        List<String> appNames = new ArrayList<>();
        List<String> appPackageNames = new ArrayList<>();

        for (PackageInfo packageInfo : packageInfoList) {
            if (cbShowSystemApps.isChecked() || ((packageInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0)) {
                String appName = packageInfo.applicationInfo.loadLabel(packageManager).toString();
                String packageName = packageInfo.packageName;
                appNames.add(appName);
                appPackageNames.add(packageName);
            }
        }

        final String[] appNamesArray = appNames.toArray(new String[0]);
        final String[] appPackageNamesArray = appPackageNames.toArray(new String[0]);

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("选择应用");
        builder.setItems(appNamesArray, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String selectedAppName = appNamesArray[which];
                selectedPackageName = appPackageNamesArray[which];
                tvSelectedApp.setText(selectedAppName + " (" + selectedPackageName + ")");
                Log.d("showAppListDialog", selectedPackageName);

                isDaemonCleared = false; // 重置标志位
                startAppMonitoringIfPossible();
            }
        });
        builder.show();
    }

    private void startAppMonitoringIfPossible() {
        if (selectedPackageName != null && !selectedPackageName.isEmpty() && !isDaemonCleared) {
            String intervalStr = etCheckInterval.getText().toString();
            try {
                int interval = Integer.parseInt(intervalStr);
                startAppMonitoring(interval);
            } catch (NumberFormatException e) {
                Log.e(TAG, "Invalid interval value: " + intervalStr);
                Toast.makeText(MainActivity.this, "无效的检测间隔值", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void checkAutoStartReceiverStatus() {
        ComponentName receiver = new ComponentName(this, AutoStartReceiver.class);
        PackageManager pm = getPackageManager();

        int componentEnabledSetting = pm.getComponentEnabledSetting(receiver);
        String status;

        switch (componentEnabledSetting) {
            case PackageManager.COMPONENT_ENABLED_STATE_ENABLED:
                status = "ENABLED";
                break;
            case PackageManager.COMPONENT_ENABLED_STATE_DISABLED:
                status = "DISABLED";
                break;
            case PackageManager.COMPONENT_ENABLED_STATE_DEFAULT:
                status = "DEFAULT (should be enabled in manifest)";
                break;
            default:
                status = "UNKNOWN";
        }

        Log.d(TAG, "AutoStartReceiver status: " + status);
    }

    private void requestNecessaryPermissions() {
        // 请求通知权限 (Android 13+)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_NOTIFICATION_PERMISSION);
            }
        }

        // 请求忽略电池优化
        requestIgnoreBatteryOptimization();

        // 请求UsageStats权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (!hasUsageStatsPermission()) {
                Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
                startActivityForResult(intent, REQUEST_USAGE_STATS_PERMISSION);
            }
        }
    }

    private boolean hasUsageStatsPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            UsageStatsManager usageStatsManager = (UsageStatsManager) getSystemService(Context.USAGE_STATS_SERVICE);
            long currentTime = System.currentTimeMillis();
            List<UsageStats> stats = usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, currentTime - 1000 * 10, currentTime);
            return stats != null && !stats.isEmpty();
        }
        return false;
    }

    private void requestIgnoreBatteryOptimization() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (powerManager != null && !powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
                try {
                    Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
                    intent.setData(Uri.parse("package:" + getPackageName()));
                    startActivityForResult(intent, REQUEST_BATTERY_OPTIMIZATION);
                } catch (Exception e) {
                    Log.e(TAG, "Failed to request battery optimization: " + e.getMessage());
                }
            }
        }
    }

    private void initAutoStartSwitch() {
        switchAutoStart = findViewById(R.id.switchAutoStart);

        // 从SharedPreferences读取开关状态
        boolean isAutoStartEnabled = sharedPreferences.getBoolean(KEY_AUTO_START, false);
        switchAutoStart.setChecked(isAutoStartEnabled);

        Log.d(TAG, "Auto start switch initialized with value: " + isAutoStartEnabled);

        // 设置开关状态改变监听器
        switchAutoStart.setOnCheckedChangeListener((buttonView, isChecked) -> {
            Log.d(TAG, "Auto start switch changed to: " + isChecked);

            // 保存开关状态到SharedPreferences
            sharedPreferences.edit().putBoolean(KEY_AUTO_START, isChecked).apply();

            if (isChecked) {
                enableAutoStart();
            } else {
                disableAutoStart();
            }
        });
    }

    private void initDaemonStartSwitch() {
        switchDaemonStart = findViewById(R.id.switchDaemonStart);

        // 从SharedPreferences读取开关状态
        boolean isDaemonStartEnabled = sharedPreferences.getBoolean(KEY_DAEMON_START, false);
        switchDaemonStart.setChecked(isDaemonStartEnabled);

        Log.d(TAG, "Daemon start switch initialized with value: " + isDaemonStartEnabled);

        // 设置开关状态改变监听器
        switchDaemonStart.setOnCheckedChangeListener((buttonView, isChecked) -> {
            Log.d(TAG, "Daemon start switch changed to: " + isChecked);

            // 保存开关状态到SharedPreferences
            sharedPreferences.edit().putBoolean(KEY_DAEMON_START, isChecked).apply();

            if (isChecked) {
                startForegroundService();
            } else {
                stopForegroundService();
            }
        });
    }

    private void startForegroundService() {
        try {
            Intent serviceIntent = new Intent(this, ForegroundService.class);
            serviceIntent.putExtra("startedBy", "MainActivity");

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                startForegroundService(serviceIntent);
            } else {
                startService(serviceIntent);
            }
            Log.d(TAG, "Foreground service started");
        } catch (Exception e) {
            Log.e(TAG, "Failed to start foreground service: " + e.getMessage());
            Toast.makeText(this, "启动服务失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    private void stopForegroundService() {
        try {
            Intent serviceIntent = new Intent(this, ForegroundService.class);
            stopService(serviceIntent);
            Log.d(TAG, "Foreground service stopped");
        } catch (Exception e) {
            Log.e(TAG, "Failed to stop foreground service: " + e.getMessage());
            Toast.makeText(this, "停止服务失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 启用开机自启动
     */
    private void enableAutoStart() {
        try {
            ComponentName receiver = new ComponentName(this, AutoStartReceiver.class);
            PackageManager pm = getPackageManager();

            // 启用BroadcastReceiver
            pm.setComponentEnabledSetting(receiver,
                    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

            Log.d(TAG, "Auto start enabled via PackageManager");

            // 验证设置是否生效
            int newState = pm.getComponentEnabledSetting(receiver);
            Log.d(TAG, "New receiver state: " + newState);

            Toast.makeText(this, "开机自启动已启用", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            Log.e(TAG, "Failed to enable auto start: " + e.getMessage());
            Toast.makeText(this, "启用开机自启动失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();

            // 提示用户手动设置开机自启
            new AlertDialog.Builder(this)
                    .setTitle("开机自启设置")
                    .setMessage("自动设置开机自启失败，请手动在系统设置中开启该应用的开机自启权限。")
                    .setPositiveButton("确定", null)
                    .show();
        }
    }

    /**
     * 禁用开机自启动
     */
    private void disableAutoStart() {
        try {
            ComponentName receiver = new ComponentName(this, AutoStartReceiver.class);
            PackageManager pm = getPackageManager();

            // 禁用BroadcastReceiver
            pm.setComponentEnabledSetting(receiver,
                    PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);

            Log.d(TAG, "Auto start disabled via PackageManager");

            // 验证设置是否生效
            int newState = pm.getComponentEnabledSetting(receiver);
            Log.d(TAG, "New receiver state: " + newState);

            Toast.makeText(this, "开机自启动已禁用", Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            Log.e(TAG, "Failed to disable auto start: " + e.getMessage());
            Toast.makeText(this, "禁用开机自启动失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
            e.printStackTrace();
        }
    }

    /**
     * 检查开机自启动是否已启用
     */
    private boolean isAutoStartEnabled() {
        ComponentName receiver = new ComponentName(this, AutoStartReceiver.class);
        PackageManager pm = getPackageManager();

        int componentEnabledSetting = pm.getComponentEnabledSetting(receiver);
        return componentEnabledSetting == PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_NOTIFICATION_PERMISSION) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(this, "通知权限已获取", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "通知权限被拒绝，可能影响功能", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_BATTERY_OPTIMIZATION) {
            PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
            if (powerManager != null && powerManager.isIgnoringBatteryOptimizations(getPackageName())) {
                Toast.makeText(this, "电池优化已忽略", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "建议忽略电池优化以保证功能正常", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == REQUEST_USAGE_STATS_PERMISSION) {
            if (!hasUsageStatsPermission()) {
                Toast.makeText(this, "未授予UsageStats权限，可能影响应用监控功能", Toast.LENGTH_LONG).show();
            }
        } else if (requestCode == REQUEST_OVERLAY_PERMISSION) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && Settings.canDrawOverlays(this)) {
                startFloatingWindowService();
            } else {
                Toast.makeText(this, "未授予悬浮窗权限，无法显示悬浮窗", Toast.LENGTH_SHORT).show();
                switchShowFloatingWindow.setChecked(false);
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        String startedBy = intent.getStringExtra("startedBy");
        if ("AutoStartReceiver".equals(startedBy)) {
            Log.d(TAG, "Activity brought to foreground by AutoStartReceiver");
        }
    }

    private void startAppMonitoring(int interval) {
        if (selectedPackageName != null && !selectedPackageName.isEmpty() && !isDaemonCleared) {
            if (appLauncher != null) {
                appLauncher.stopMonitoring();
            }
            Log.d("AppLauncher", "startAppMonitoring: " + selectedPackageName + ", interval: " + interval);
            appLauncher = new AppLauncher(this, interval);
            appLauncher.startMonitoring();
        }
    }

    /**
     * 关闭目标应用程序
     */
    public void closeTargetApp() {

        try {
            if (selectedPackageName != null && !selectedPackageName.isEmpty()) {
                Log.d(TAG, "Trying to close app with package name: " + selectedPackageName);
                ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    activityManager.killBackgroundProcesses(selectedPackageName);
                } else {
                    // 旧版本的兼容处理
                    try {
                        activityManager.restartPackage(selectedPackageName);

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                Log.d(TAG, "Closed target app: " + selectedPackageName);
            }
            if (selectedPackageName != null && !selectedPackageName.isEmpty()) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", selectedPackageName, null);
                intent.setData(uri);
                startActivity(intent);
                Log.d(TAG, "Opened app details settings for: " + selectedPackageName);
            } else {
                Log.e(TAG, "Selected package name is null or empty.");
            }
        }catch (Exception e) {

            Log.e(TAG, "close target app error");
        }
    }

    private void requestOverlayPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
            new AlertDialog.Builder(this)
                    .setTitle("悬浮窗权限")
                    .setMessage("需要授予悬浮窗权限才能正常使用该功能")
                    .setPositiveButton("去授予", (dialog, which) -> {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
                        startActivityForResult(intent, REQUEST_OVERLAY_PERMISSION);
                    })
                    .setNegativeButton("取消", (dialog, which) -> switchShowFloatingWindow.setChecked(false))
                    .show();
        } else {
            startFloatingWindowService();
        }
    }

    /**
     * 清除选定的目标应用包名
     */
    public void clearSelectedPackageName() {
        selectedPackageName = null;

        tvSelectedApp.setText("未选择程序");
        if (appLauncher != null) {
            appLauncher.stopMonitoring();
        }
        appLauncher = new AppLauncher(this, 10);
        appLauncher.stopMonitoring();
        isDaemonCleared = true; // 设置标志位
        Log.d(TAG, "Selected package name cleared.");
    }

}